/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.fzhucc.modules.pms.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.pms.domain.Project;
import com.fzhucc.modules.pms.domain.ProjectService;
import com.fzhucc.modules.pms.domain.dto.ProjectServiceWithProjectIdDto;
import com.fzhucc.modules.pms.repository.ProjectRepository;
import com.fzhucc.modules.technical.domain.Technical;
import com.fzhucc.modules.technical.repository.TechnicalRepository;
import com.fzhucc.utils.ValidationUtil;
import com.fzhucc.utils.FileUtil;
import com.fzhucc.utils.PageUtil;
import com.fzhucc.utils.QueryHelp;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.pms.repository.ProjectServiceRepository;
import com.fzhucc.modules.pms.domain.dto.ProjectServiceDto;
import com.fzhucc.modules.pms.domain.dto.ProjectServiceQueryCriteria;
import com.fzhucc.modules.pms.service.mapstruct.ProjectServiceMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author yyg
* @date 2022-12-13
**/
@Service
@RequiredArgsConstructor
public class ProjectServiceService {

    private final ProjectServiceRepository projectServiceRepository;
    private final ProjectServiceMapper projectServiceMapper;

    private final TechnicalRepository technicalRepository;

    private final ProjectRepository projectRepository;

    public Map<String,Object> queryAll(ProjectServiceQueryCriteria criteria, Pageable pageable){
        Page<ProjectService> page = projectServiceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Page<ProjectServiceDto> map = page.map(projectServiceMapper::toDto);
        List<ProjectServiceDto> list = map.getContent();
        for (int i = 0; i < list.size(); i++) {
            ProjectServiceDto projectServiceDto = list.get(i);
            projectServiceDto.setProject(projectRepository.findById(projectServiceDto.getProjectId()).get());
            projectServiceDto.setTechnical(technicalRepository.findById(projectServiceDto.getTechnicalId()).get());
        }
        return PageUtil.toPage(map);
    }

    public Map<String,Object> queryProjectByProjectId(ProjectServiceWithProjectIdDto projectServiceWithProjectIdDto, Pageable pageable){
        String projectId = projectServiceWithProjectIdDto.getProjectId();
        if (projectId==null || projectId.equals("")){
            throw new BadRequestException("未找到项目ID");
        }
        Page<ProjectService> page = projectServiceRepository.findAllByProjectId(projectId, pageable);
        Page<ProjectServiceDto> map = page.map(projectServiceMapper::toDto);
        List<ProjectServiceDto> list = map.getContent();
        for (int i = 0; i < list.size(); i++) {
            ProjectServiceDto projectServiceDto = list.get(i);
            projectServiceDto.setTechnical(technicalRepository.findById(projectServiceDto.getTechnicalId()).get());
        }
        return PageUtil.toPage(map);
    }

    public List<ProjectServiceDto> queryAll(ProjectServiceQueryCriteria criteria){
        return projectServiceMapper.toDto(projectServiceRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    public ProjectServiceDto findById(Integer id) {
        ProjectService projectService = projectServiceRepository.findById(id).orElseGet(ProjectService::new);
        ValidationUtil.isNull(projectService.getId(),"ProjectService","id",id);
        return projectServiceMapper.toDto(projectService);
    }

    @Transactional(rollbackFor = Exception.class)
    public ProjectServiceDto create(ProjectService resources) {
        Optional<Project> resProject = projectRepository.findById(resources.getProjectId());
        if (resProject.isEmpty()){
            throw new BadRequestException("未找到项目");
        }
        if (resources.getTechnicalId()!=null && resources.getTechnicalId()!=0){
            Optional<Technical> res = technicalRepository.findById(resources.getTechnicalId());
            if (res.isEmpty()){
                throw new BadRequestException("未找到技术经理人");
            }
        }
        return projectServiceMapper.toDto(projectServiceRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(ProjectService resources) {
        Optional<Project> resProject = projectRepository.findById(resources.getProjectId());
        if (resProject.isEmpty()){
            throw new BadRequestException("未找到项目");
        }
        if (resources.getTechnicalId()!=null && resources.getTechnicalId()!=0){
            Optional<Technical> res = technicalRepository.findById(resources.getTechnicalId());
            if (res.isEmpty()){
                throw new BadRequestException("未找到技术经理人");
            }
        }
        ProjectService projectService = projectServiceRepository.findById(resources.getId()).orElseGet(ProjectService::new);
        ValidationUtil.isNull( projectService.getId(),"ProjectService","id",resources.getId());
        projectService.copy(resources);
        projectServiceRepository.save(projectService);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            projectServiceRepository.deleteById(id);
        }
    }

    public void download(List<ProjectServiceDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProjectServiceDto projectService : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("项目id", projectService.getProjectId());
            map.put("服务时间", projectService.getServiceTime());
            map.put("技术经理人id", projectService.getTechnicalId());
            map.put("备注", projectService.getServiceDesc());
            map.put("附件", projectService.getUrl());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}